<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/15
 * Time: 11:56
 */

namespace process;


use Workerman\Crontab\Crontab;
use Workerman\Timer;

class Task
{
    public function onWorkerStart($worker)
    {
        // 拿到当前进程的id编号.
        $workid = $worker->id;
        // 获取所有定时器任务配置.
        $timedTask = require_once(runtime_path('crontab.php'));
        if (is_array($timedTask)) {
            // 循环检测任务绑定.
            foreach ($timedTask as $key => $value) {
                // 绑定任务进程.
                if ($value['worker_id'] == $workid) {
                    if(is_numeric($value['time'])){
                        if(is_string($value['callback'])){
                            Timer::add(intval($value['time']), [Task::class,'execCallback'],$value['callback']);
                        }else{
                            Timer::add(intval($value['time']), $value['callback']);
                        }
                    }else{
                        if(is_string($value['callback'])){
                            $callback = $value['callback'];
                            new Crontab($value['time'], function ()use($callback){
                                return Task::execCallback($callback);
                            },$key);
                        }else{
                            new Crontab($value['time'], $value['callback'],$key);
                        }
                    }
                }
            }
        }
    }

    public static function execCallback($callback)
    {
        //file_put_contents(runtime_path('execCallback'),$callback.'  '.date('Y-m-d H:i:s')."\n",8);
        exec($callback.' 2>&1 &', $output);
    }
}